package com.wzh.apiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.wzh.apiclientsdk.model.User;
import com.wzh.apiclientsdk.utils.SignUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author wzh
 * @create 2023/4/5 20:46
 * @Description:调用第三方接口的客户端
 */
public class ApiClient {

    private String accessKey;

    private String secretKey;

    private static final String GATEWAY_HOST="http://localhost:8090";

    public ApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getNameByGet(String name) {
        // 最简单的HTTP请求，可以自动通过header等信息判断编码，不区分HTTP和HTTPS
//        String result1= HttpUtil.get("https://www.baidu.com");

        // 当无法识别页面编码的时候，可以自定义请求页面的编码
//        String result2= HttpUtil.get("https://www.baidu.com", CharsetUtil.CHARSET_UTF_8);

        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result3 = HttpUtil.get(GATEWAY_HOST+"/api/name/", paramMap);
        System.out.println(result3);
        return result3;

    }

    public Map<String, String> getHeadMap(String body) {
        Map<String, String> headMap = new HashMap<>();
        headMap.put("accessKey", accessKey);
//        一定不能直接发送
//        headMap.put("secretKey", secretKey);
        headMap.put("nonce", RandomUtil.randomNumbers(4));
        headMap.put("body", body);
        headMap.put("timestamp", String.valueOf(System.currentTimeMillis()/1000));
        headMap.put("sign", SignUtils.genSign(body,secretKey));
        return headMap;
    }




    public String getNameByPost(String name) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result3 = HttpUtil.post(GATEWAY_HOST+"/api/name/", paramMap);
        System.out.println(result3);
        return result3;
    }


    public String getUsernameByPost( User user) {
        String json = JSONUtil.toJsonStr(user);
        HttpResponse execute = HttpRequest.post(GATEWAY_HOST+"/api/name/user")
                .addHeaders(getHeadMap(json))
                .body(json)
                .execute();
        System.out.println(execute.getStatus());
        String result = execute.body();
        System.out.println(result);
        return result;
    }
}
